package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MD5Util;
import com.ruoyi.common.utils.MoneyUtil;
import org.bouncycastle.asn1.cms.RecipientInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class AliWlOrderCheckTask {


    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate = 5000)
    public void checkOrder() throws Exception {
//        logger.info("万丽订单查询..");
        Calendar c = Calendar.getInstance();
        TOrderInfo orderquery = new TOrderInfo();
        orderquery.setChannelType("alipay");
        orderquery.setChannel("alipay_wl_h5");
        orderquery.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(orderquery);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//要转换的时间格式
        for (TOrderInfo orderInfo : orderInfos) {
            TRecipientInfo recipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String url = "https://shouyin.zmwanli.com/index.php/store/StoreOrder/index";
            String cookieStr = recipientInfo.getCookie();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String access_token = cookieObj.getString("access_token");
            HashMap<String, String> headerMap = new HashMap();
            headerMap.put("User-Agent", "wan li shou yin/1.0.7 (iPhone; iOS 15.5; Scale/3.00)");
            HashMap<String, String> dataMap = new HashMap();
            dataMap.put("access_token",access_token);
            dataMap.put("client_type","2");
            dataMap.put("client_version","1.0.7");
            dataMap.put("end_minute","23:59");
            dataMap.put("end_time",sdf.format(new Date()));
            dataMap.put("limit","50");
            dataMap.put("oem_app_id","2");
            dataMap.put("page","1");
            dataMap.put("pay_status","1");
            dataMap.put("start_minute","00:00");
            dataMap.put("start_time",sdf.format(new Date()));
//            logger.info("万丽订单查询请求：" + queryObj.toJSONString());
            StringBuilder buf = new StringBuilder("");
            HttpUtils.buildPayParams(buf, dataMap);
            String preStr = buf.toString();
//            logger.info("请求参数："+preStr);
            String httpResponse = HttpUtils.sendPostRequest(url,preStr, headerMap);
            JSONObject resultObj = JSONObject.parseObject(httpResponse);
//            logger.info("万丽订单查询.." + resultObj);
            int resultCode = resultObj.getInteger("code");
            if (resultCode == 200 ) {
                    JSONArray recordList = resultObj.getJSONObject("data").getJSONArray("itemList");
                    for (int i = 0; i < recordList.size(); i++) {
                        JSONObject recordObj = recordList.getJSONObject(i);
                        if (recordObj.getString("pay_status").equals("1") && orderInfo.getRealMoney().equals(recordObj.getLong("order_fee"))) {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String pay_time = timeStamp2Date(recordObj.getString("pay_time"));
                            logger.info("insertDateStr.." + pay_time);
                            Date createTime = orderInfo.getCreateTime();
                            Date validTime = orderInfo.getValidTime();
                            Date insertDate = dateFormat.parse(pay_time);
                            logger.info("万丽订单创建时间.." + dateFormat.format(createTime));
                            logger.info("万丽订单失效时间.." + dateFormat.format(validTime));
                            logger.info("万丽订单回调时间.." + dateFormat.format(insertDate));
                            //insertDate  判断账单时间大于订单生成时间
                            int k = insertDate.compareTo(createTime);
                            //insertDate  判断账单时间小于订单失效时间
                            int k1 = insertDate.compareTo(validTime);
                            logger.info("万丽订单回调时间是否大于创建时间：" + k);
                            logger.info("万丽订单回调时间是否小于失效时间：" + k1);
                            if (k > 0 && k1 < 0) {
                                logger.info("万丽订单查询.." + recordObj);
                                MsgPayResult msgPayResult = new MsgPayResult();
                                msgPayResult.setChannel(orderInfo.getChannel());
                                msgPayResult.setTradeNo(orderInfo.getId().toString());
                                msgPayResult.setChannelAccount(recipientInfo.getChannelAccount());
                                msgPayResult.setOrderId(recordObj.getString("order_no"));
                                msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getRealMoney() + ""));
                                msgPayResult.setUid(recipientInfo.getUserId().toString());
                                msgPayResult.setBillTime(pay_time);

                                msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                                chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                                chargeService.notifyUserPaySucc(orderInfo.getId());

                                logger.info("万丽订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getRealMoney());
                                //查询是否有风控标志 risk_status
                                logger.info("万丽订单号：" + orderInfo.getId() + " 风控状态:" + recordObj.getString("risk_status")+"  风控内容："+recordObj.getString("risk_text"));
                                if(recordObj.getIntValue("risk_status")!=0){
                                    recipientInfo.setChannelDisabled(1);
                                    recipientInfo.setDisabledInfo(recordObj.getString("risk_text"));
                                    userRecipientService.updateTRecipientInfo(recipientInfo);
                                }
                                break;
                            }
                        }
                }
            }else {
                String accountJson = recipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                cookieObj = new JSONObject();
                String passport = recipientInfo.getChannelAccount().split("_")[0];

                //https://www.shouyinbei.net/api/userInfo/13950341396/Ldw834391
                url = "https://shouyin.zmwanli.com/index.php/store/Account/login";
                dataMap = new HashMap<>();
                dataMap.put("client_no", MD5Util.stringMD5(passport));
                dataMap.put("client_type", "2");
                dataMap.put("client_version", "1.0.7");
                dataMap.put("mobile", passport);
                dataMap.put("oem_app_id", "2");
                dataMap.put("oem_no", "wannengbang");
                dataMap.put("password", accountObj.getString("password"));
                buf = new StringBuilder("");
                HttpUtils.buildPayParams(buf, dataMap);
                preStr = buf.toString();
                logger.info("万丽登录请求参数：" + preStr);
                HttpResponse loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "万丽登录", "");
                resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
                logger.info("万丽登录返回:" + resultObj);
                if (resultObj.getIntValue("code") != 200) {
                    continue;
                }
                JSONObject data = resultObj.getJSONObject("data");
                access_token = data.getString("access_token");
                cookieObj.put("access_token", access_token);
                //access_token=3V50JI0KBN2JRD7JS8KT2PVKKP&client_type=2&client_version=1.0.7&limit=50&oem_app_id=2&page=1
                //https://shouyin.zmwanli.com/index.php/store/DeviceUnify/index
                url = "https://shouyin.zmwanli.com/index.php/store/Store/me";
                dataMap = new HashMap<>();
                dataMap.put("access_token", access_token);
                dataMap.put("client_type", "2");
                dataMap.put("client_version", "1.0.7");
                dataMap.put("oem_app_id", "2");
                loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "万丽登录", "");
                resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
                if (resultObj.getIntValue("code") != 200) {
                    continue;
                }
                recipientInfo.setChannelAccount(passport + "_" + resultObj.getJSONObject("data").getString("name")+"_"+resultObj.getJSONObject("data").getString("store_no"));
                //获取码牌
                url = "https://shouyin.zmwanli.com/index.php/store/DeviceUnify/index";
                dataMap = new HashMap<>();
                dataMap.put("access_token", access_token);
                dataMap.put("client_type", "2");
                dataMap.put("client_version", "1.0.7");
                dataMap.put("limit", "50");
                dataMap.put("oem_app_id", "2");
                dataMap.put("page", "1");
                loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "万丽登录", "");
                resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
                logger.info("万丽获取码牌返回:" + resultObj);
                if (resultObj.getIntValue("code") != 200) {
                    continue;
                }
                JSONArray itemList = resultObj.getJSONObject("data").getJSONArray("itemList");
                if (itemList.size() > 0) {
                    JSONObject itemObj = (JSONObject) itemList.get(0);
                    String qrurl = itemObj.getString("qrurl");
                    String bind_store_no = itemObj.getString("bind_store_no");
                    String wlid = itemObj.getString("id");
                    cookieObj.put("qrurl", qrurl);
                    cookieObj.put("bind_store_no", bind_store_no);
                    cookieObj.put("id", wlid);
                }
                recipientInfo.setOnline(1);
                recipientInfo.setCardNo(null);
                recipientInfo.setCookie(cookieObj.toJSONString());
                userRecipientService.updateTRecipientInfo(recipientInfo);

                //获取所有店铺
                //https://shouyin.zmwanli.com/index.php/store/Store/index

                dataMap = new HashMap<>();
                dataMap.put("access_token", access_token);
                dataMap.put("client_type", "2");
                dataMap.put("client_version", "1.0.7");
                dataMap.put("limit", "100");
                dataMap.put("oem_app_id", "2");
                dataMap.put("page", "1");
                buf = new StringBuilder("");
                HttpUtils.buildPayParams(buf, dataMap);
                preStr = buf.toString();
                logger.info("万丽获取店铺请求参数：" + preStr);
                url = "https://shouyin.zmwanli.com/index.php/store/Store/index";
                loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "万丽登录", "");
                resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
//            logger.info("万丽获取店铺返回:" + resultObj);
                if (resultObj.getIntValue("code") != 200) {
                    continue;
                }

                JSONArray storList = resultObj.getJSONObject("data").getJSONArray("itemList");
                String queryStroeNo = resultObj.getJSONObject("data").getString("name");
                String queryToken = access_token;
                for (int i = 0; i < storList.size()-1; i++) {
                    JSONObject merObj = storList.getJSONObject(i);
                    if(merObj.getIntValue("sign_status")!=2){
                        continue;
                    }
                    TRecipientInfo query = new TRecipientInfo();
                    query.setChannelAccount(passport + "_" + merObj.getString("name")+"_"+merObj.getString("store_no"));
                    query.setChannel("alipay_wl_h5");
                    List<TRecipientInfo> RecipientInfoList = userRecipientService.selectTRecipientInfoList(query);

                    if (RecipientInfoList.size() == 0) {
                        cookieObj = new JSONObject();
                        //切换stroe
                        url = "https://shouyin.zmwanli.com/index.php/store/Store/changeStore";
                        dataMap = new HashMap<>();
                        dataMap.put("access_token", queryToken);
                        dataMap.put("client_type", "2");
                        dataMap.put("client_version", "1.0.7");
                        dataMap.put("oem_app_id", "2");
                        dataMap.put("store_no", merObj.getString("store_no"));
                        loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "万丽切换store", "");
                        resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
                        logger.info("从" + queryStroeNo + "切换到" + merObj.getString("name") + "万丽切换store返回:" + resultObj);
                        if (resultObj.getIntValue("code") != 200) {
                            continue;
                        }
                        queryStroeNo = merObj.getString("name");
                        queryToken = resultObj.getJSONObject("data").getString("access_token");
                        cookieObj.put("access_token", queryToken);
                        TRecipientInfo newRecipientInfo = new TRecipientInfo();
                        BeanUtils.copyProperties(recipientInfo, newRecipientInfo);
                        newRecipientInfo.setId(null);
                        newRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("name")+"_"+merObj.getString("store_no"));
                        newRecipientInfo.setOnline(1);
                        //获取码牌
                        url = "https://shouyin.zmwanli.com/index.php/store/DeviceUnify/index";
                        dataMap = new HashMap<>();
                        dataMap.put("access_token", queryToken);
                        dataMap.put("client_type", "2");
                        dataMap.put("client_version", "1.0.7");
                        dataMap.put("limit", "50");
                        dataMap.put("oem_app_id", "2");
                        dataMap.put("page", "1");
                        loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "万丽登录", "");
                        resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
                        logger.info("万丽获取码牌返回:" + resultObj);
                        if (resultObj.getIntValue("code") != 200) {
                            continue;
                        }
                        itemList = resultObj.getJSONObject("data").getJSONArray("itemList");
                        if (itemList.size() > 0) {
                            JSONObject itemObj = (JSONObject) itemList.get(0);
                            String qrurl = itemObj.getString("qrurl");
                            String bind_store_no = itemObj.getString("bind_store_no");
                            String wlid = itemObj.getString("id");
                            cookieObj.put("qrurl", qrurl);
                            cookieObj.put("bind_store_no", bind_store_no);
                            cookieObj.put("id", wlid);
                        }
                        newRecipientInfo.setOnline(1);
                        newRecipientInfo.setCookie(cookieObj.toJSONString());
                        userRecipientService.insertTRecipientInfo(newRecipientInfo);
                    } else {
                        TRecipientInfo recipientInfo1 = RecipientInfoList.get(0);
                        cookieObj = JSONObject.parseObject(recipientInfo1.getCookie());
                        url = "https://shouyin.zmwanli.com/index.php/store/Store/changeStore";
                        dataMap = new HashMap<>();
                        dataMap.put("access_token", queryToken);
                        dataMap.put("client_type", "2");
                        dataMap.put("client_version", "1.0.7");
                        dataMap.put("oem_app_id", "2");
                        dataMap.put("store_no", merObj.getString("store_no"));
                        loginHttpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "万丽切换store", "");
                        resultObj = JSONObject.parseObject(loginHttpResponse.getDocument().body().text());
                        logger.info("万丽切换store返回:" + resultObj);
                        if (resultObj.getIntValue("code") != 200) {
                            continue;
                        }
                        queryToken = resultObj.getJSONObject("data").getString("access_token");

                        cookieObj.put("access_token", queryToken);
                        recipientInfo1.setOnline(1);
                        recipientInfo1.setCookie(cookieObj.toJSONString());
                        userRecipientService.updateTRecipientInfo(recipientInfo1);
                    }

                }
            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


}
